﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace InSys.Documents
{
    public partial class FormEditLinkDocument : Form
    {
        public FormEditLinkDocument()
        {
            InitializeComponent();
            InitData();
        }

        private MapTestLinqDataContext db;
        private document currentDocument;
        private IEnumerable<document> listParentDocuments;
        private IEnumerable<document> listChildDocuments;

        public MapTestLinqDataContext DataContext
        {
            get
            {
                return db;
            }
            set
            {
                db = value;
            }
        }

        /// <summary>
        /// Текущий активный документ, для которого отображаются родительские и дочерние элементы
        /// </summary>
        public document CurrentDocument
        {
            get
            {
                return currentDocument;
            }
            set
            {
                currentDocument = value;
                InitData();
            }
        }

        private document SelectDocument()
        {
            document result = null;
            FormSelectDocument frm = new FormSelectDocument();
            frm.DataContext = db;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                result = frm.SelectedDocument;
            }
            return result;
        }

        private bool CheckExisting(document doc1, document doc2)
        {
            parentDocumentLink link;
            if (null == doc1 || null == doc2) return false;
            link = FindLink(doc1, doc2);
            if (null != link) return true;
            link = FindLink(doc2, doc1);
            if (null != link) return true;
            return false;
        }

        private parentDocumentLink FindLink(document parent, document child)
        {
            parentDocumentLink result = null;
            if (null == parent || null == child) return null;
            result = (from item in db.parentDocumentLink where item.id_child_document == child.id_document && item.id_parent_document == parent.id_document select item).FirstOrDefault();
            return result;
        }

        private void bindingNavigatorAddParentNewItem_Click(object sender, EventArgs e)
        {
            parentDocumentLink addedItem = null;
            try
            {
                document selectedParentDocument = SelectDocument();
                if (null == selectedParentDocument) return;
                if (CheckExisting(selectedParentDocument, CurrentDocument) == true)
                {
                    MessageBox.Show("Выбранный документ уже связан с текущим документом.");
                    return;
                }
                addedItem = new parentDocumentLink();
                if (addedItem == null) throw new Exception();
                addedItem.document = CurrentDocument;
                addedItem.document1 = selectedParentDocument;
                db.parentDocumentLink.InsertOnSubmit(addedItem);
                db.SubmitChanges();
                InitData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка добавления документа.");
            }
        }

        private void bindingNavigatorDeleteParentItem_Click(object sender, EventArgs e)
        {
            document parent;
            parentDocumentLink link;
            if (null == parentDocumentBindingSource.DataSource) return;
            try
            {
                parent = (parentDocumentBindingSource.Current as document);
                link = FindLink(parent, CurrentDocument);
                if (null == link) return;
                db.parentDocumentLink.DeleteOnSubmit(link);
                db.SubmitChanges();
                InitData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка удаления связи.");
            }
        }

        private void toolStripButtonParentEdit_Click(object sender, EventArgs e)
        {
            document parent;
            parentDocumentLink link;
            if (null == parentDocumentBindingSource.DataSource) return;
            try
            {
                parent = parentDocumentBindingSource.Current as document;
                link = FindLink(parent, CurrentDocument);
                if (null == link) return;
                parent = SelectDocument();
                if (null == parent || parent == CurrentDocument) return;
                if (CheckExisting(parent, CurrentDocument) == true)
                {
                    MessageBox.Show("Выбранный документ уже связан с текущим документом.");
                    return;
                }
                link.document1 = parent;
                db.SubmitChanges();
                InitData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка изменения документа.");
            }

        }

        private void bindingNavigatorAddNewChildItem_Click(object sender, EventArgs e)
        {
            parentDocumentLink addedItem = null;
            try
            {
                document selectedChildDocument = SelectDocument();
                if (null == selectedChildDocument) return;
                if (CheckExisting(selectedChildDocument, CurrentDocument) == true)
                {
                    MessageBox.Show("Выбранный документ уже связан с текущим документом.");
                    return;
                }
                addedItem = new parentDocumentLink();
                if (addedItem == null) throw new Exception();
                addedItem.document = selectedChildDocument;
                addedItem.document1 = CurrentDocument;
                db.parentDocumentLink.InsertOnSubmit(addedItem);
                db.SubmitChanges();
                InitData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка добавления документа.");
            }
        }

        private void bindingNavigatorDeleteChildItem_Click(object sender, EventArgs e)
        {
            document child;
            parentDocumentLink link;
            if (null == childDocumentBindingSource.DataSource) return;
            try
            {
                child = (childDocumentBindingSource.Current as document);
                link = FindLink(CurrentDocument, child);
                if (null == link) return;
                db.parentDocumentLink.DeleteOnSubmit(link);
                db.SubmitChanges();
                InitData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка удаления связи.");
            }
        }

        private void toolStripButtonchildEdit_Click(object sender, EventArgs e)
        {
            document child;
            parentDocumentLink link;
            if (null == childDocumentBindingSource.DataSource) return;
            try
            {
                child = childDocumentBindingSource.Current as document;
                link = FindLink(CurrentDocument, child);
                if (null == link) return;
                child = SelectDocument();
                if (null == child || child == CurrentDocument) return;
                if (CheckExisting(child, CurrentDocument) == true)
                {
                    MessageBox.Show("Выбранный документ уже связан с текущим документом.");
                    return;
                }
                link.document = child;
                db.SubmitChanges();
                InitData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка изменения документа.");
            }
        }

        private void InitData()
        {
            FormWaitWindow wnd;
            listParentDocuments = null;
            listChildDocuments = null;
            childDocumentBindingSource.DataSource = typeof(document);
            parentDocumentBindingSource.DataSource = typeof(document);

            if (null == currentDocument) return;
            wnd = new FormWaitWindow();
            wnd.Description = "Поиск документа. Подождите.";
            wnd.Show();

            backgroundWorkerInitData.RunWorkerAsync();
            while (backgroundWorkerInitData.IsBusy)
            {
                Application.DoEvents();
            }
            wnd.Close();
            wnd = null;
            parentDocumentBindingSource.DataSource = listParentDocuments;
            childDocumentBindingSource.DataSource = listChildDocuments;
        }

        private void BackgroundInitData()
        {
            listParentDocuments = ClassWorkWithDB.getParentDocuments(db, currentDocument);
            listChildDocuments = ClassWorkWithDB.getChildDocuments(db, currentDocument);
        }



        private void backgroundWorkerInitData_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundInitData();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                db.SubmitChanges();
                Close();
            }
            catch (Exception)
            {
                MessageBox.Show(Properties.Resources.DataNotSaved);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
